import { readToken, installToken } from "@/state/token";
import { updateUserInfo } from "@/state/user";
import { request } from "./request";

function isLoggedIn() {
  return readToken() !== null;
}

async function login(username, password) {
  const response = await request("/login", "POST", {
    username, password
  });
  const token = response.token;
  if (typeof token != "string") {
    throw Error("错误的请求");
  }
  const expireTime = response.expireTime;
  if (typeof expireTime != "number") {
    throw Error("错误的请求");
  }
  installToken(token, expireTime);
  updateUserInfo(response);
}

export { isLoggedIn, login };